# coding:utf-8
# py2
from __future__ import print_function
from __future__ import print_function
from __future__ import print_function
import hashlib
import json
import os
import sys
import urllib
import urllib2

reload(sys)
sys.setdefaultencoding('utf-8')

secret_key = '*'


def create_sign(params):
    """create sign using md5"""
    params = '&'.join(['%s=%s' % (key, params[key])
                       for key in sorted(params.keys())])
    content = (params + "&key=" + secret_key).encode()
    sign = hashlib.new('md5', content).hexdigest()
    return sign


def get_download_list(cid):
    # cid [必选] int, 视频 id
    # format [可选] int, 视频清晰度，为空则返回全部结果。
    # only_mp4 [可选] enum(0, 1) 表明是否对结果过滤，只取出后缀名为 mp4的文件的下载地址，默认为只返回 mp4 结果。
    # status [可选] int, 数据库记录状态，表明是否对结果过滤，只返回指定状态的记录，不传默认为健康状态（1）。对于异常状态（非1）的文件，即便生成了下载地址仍然可能是有问题的。
    params = {'cid': cid,
              }
    url = '*'
    sign = create_sign(params)
    params['sign'] = sign
    params = urllib.urlencode(params)
    print(url + '?' + params)
    request = urllib2.Request(url + '?' + params)
    response = urllib2.urlopen(request)
    result = response.read()
    print(result)
    return json.loads(result)


def download_mp4(video_name, url, vedio_path):
    if os.path.exists(vedio_path):
        print('%s.mp4已存在' % video_name)
        return
    f = urllib2.urlopen(url)
    data = f.read()
    with open(vedio_path, "wb") as code:
        code.write(data)
    print('%s.mp4下载完毕，大小：%sm' % (video_name, (len(data) / (1000 * 1000))))

# if __name__ == '__main__':
#     cid = int(sys.argv[1])
#     vedio_path = '/Users/lingzhengxin/Documents/%s.mp4' % cid
#     if os.path.exists(vedio_path):
#         print '%s文件已存在' % vedio_path
#         sys.exit()
#     result = get_download_list(cid)
#     # 取下载清晰度最高的mp4视频的url地址
#     largest_format_index = 0
#     index = 0
#     for info in result[u'info']:
#         if info[u'format'] > largest_format_index:
#             largest_format_index = index
#         index += 1
#     download_url = result[u'info'][largest_format_index][u'url']
#     download_mp4(cid, download_url, vedio_path)
